package com.example.sql.manager.ftl;

import com.example.sql.manager.utils.IDUtils;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Objects;

public class FtlParser {

    public static String parseToSql(String templateContent, Map<String, Object> params) throws IOException, TemplateException {

        final String templateName = String.valueOf(IDUtils.genRandomId());

        Configuration configuration;
        StringTemplateLoader templateLoader = null;
        try {
            configuration = FtlConfigSingleton.getSingleton();
            templateLoader = (StringTemplateLoader) configuration.getTemplateLoader();
            //放入模板
            templateLoader.putTemplate(templateName, templateContent);

            StringWriter stringWriter = new StringWriter();
            Template template = configuration.getTemplate(templateName);
            template.process(params, stringWriter);
            StringBuffer buffer = stringWriter.getBuffer();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(templateLoader)) {
                //模板删除
                templateLoader.removeTemplate(templateName);
            }
        }
        return null;
    }
}
